package com.hzb.gulimall.product.web;

import com.hzb.gulimall.product.entity.CategoryEntity;
import com.hzb.gulimall.product.service.CategoryService;
import com.hzb.gulimall.product.vo.CateLog2Vo;
import org.redisson.api.RCountDownLatch;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
public class IndexController {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedissonClient redisson;

    @GetMapping({"/","/index.html"})
    public String indexPage(Model model){

        List<CategoryEntity> categoryEntities = categoryService.getCategoryList();
        model.addAttribute("categoryEntities",categoryEntities);
        return "index";
    }


    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<CateLog2Vo>> getCatalogJson(){

        Map<String, List<CateLog2Vo>> map = categoryService.getCatalogJson();
        return map;
    }

    @GetMapping("/park")
    @ResponseBody
    public String park() throws InterruptedException {

        RSemaphore park = redisson.getSemaphore("park");
        //park.acquire();//获取一个信号，获取一个值，占一个车位
        boolean b = park.tryAcquire();
        if (b){
            return "ok";
        }else {
            return "error";
        }
    }

    @GetMapping("/go")
    @ResponseBody
    public String go() throws InterruptedException {

        RSemaphore park = redisson.getSemaphore("park");
        park.release();//释放一个车位
        return "ok";
    }

}
